<template>
  <div class="main">
    <!-- <span>{{`${currentIndex}--------------------${currentPath}------------${routePath}----------${$route.matched[$route.matched.length-1].name}`}}</span> -->
    <keep-alive>
      <template v-if="keepAlive">
        <router-view v-if="routePath===currentPath"
                     :name="currentName"></router-view>
        <router-view v-else>
        </router-view>
      </template>
    </keep-alive>
    <template v-if="!keepAlive">
      <router-view v-if="routePath===currentPath"
                   :name="currentName"></router-view>
      <router-view v-else>
      </router-view>
    </template>
  </div>
</template>

<script>
export default {
  name: 'RouteView',
  data () {
    return {
      currentIndex: 0,
      currentPath: '',
      currentName: '',
      routePath: ''
    }
  },
  computed: {
    keepAlive () {
      return this.$route.meta.keepAlive === '1' || this.$store.state.app.multipage
      // return false
    }
  },
  watch: {
    $route: {
      handler: function (val, oldVal) {
        this.getCurrentInfo()
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    getCurrentInfo () {
      let matchedLength = this.$route.matched.length
      this.currentIndex = this.$vnode.data.routerViewDepth // 获取当前组件层级
      this.routePath = this.$route.path
      if (this.currentIndex < matchedLength - 1) {
        this.currentPath = this.$route.matched[this.currentIndex + 1].path
        this.currentName = this.$route.matched[matchedLength - 1].name
      } else if (this.currentIndex === matchedLength - 1) {
        this.currentPath = this.$route.matched[this.currentIndex].path
        this.currentName = this.$route.matched[matchedLength - 1].name
      } else if (!this.currentIndex) {
        this.currentPath = this.$route.matched[1].path
        this.currentName = this.$route.matched[1].name
      } // 获取当前组件path
    }
  },
  created () {

  },
  updated () {
  }
}
</script>
